# ----------------------
# 1. 生成饼图（单独保存为 pie.png）
# ----------------------
# 准备数据
categories <- c("A类", "B类", "C类", "D类", "E类")
values <- c(25, 20, 15, 30, 10)
percentages <- paste0(round(values/sum(values) * 100, 1), "%")

# 开启饼图的PNG设备（指定中文字体）
png(
  filename = "/root/rstudio/data/output/pie.png",  # 单独保存为pie.png
  width    = 800,
  height   = 600,
  res      = 150,
  family   = "Noto Sans CJK SC"  # 中文字体（Windows用"SimHei"，mac用"PingFang SC"）
)

# 绘制饼图
pie(
  values,
  labels = paste(categories, percentages, sep = "\n"),
  main = "各分类占比饼图",
  col = rainbow(length(categories)),
  clockwise = TRUE
)

# 添加图例
legend(
  "topright",
  categories,
  fill = rainbow(length(categories)),
  cex = 0.8,
  bty = "n"
)

# 关闭饼图设备（保存图片）
dev.off()


# ----------------------
# 2. 生成柱状图（单独保存为 bar.png）
# ----------------------
# 开启柱状图的PNG设备
png(
  filename = "/root/rstudio/data/output/bar.png",  # 单独保存为bar.png
  width    = 800,
  height   = 600,
  res      = 150,
  family   = "Noto Sans CJK SC"  # 保持中文字体一致
)

# 绘制柱状图
barplot(
  height = values,
  names.arg = categories,
  main = "各分类数值柱状图",
  xlab = "分类",
  ylab = "数值",
  col = terrain.colors(length(categories)),  # 与饼图颜色区分
  border = "white",
  ylim = c(0, max(values) + 5)  # 预留顶部空间放标签
)

# 柱状图顶部添加数值标签
text(
  x = 1:length(categories),
  y = values + 1,
  labels = values,
  cex = 0.8
)

# 关闭柱状图设备（保存图片）
dev.off()